<?php

namespace app\api\service;
use think\facade\{View,Session,Cache,Db};

class Wxpay{
   
        public function __construct($openid=""){
         
            
           
            $config=Db::name("wx_basic")->find(1);

            $this->shopName=$config['name'];
           
            $this->mchid=$config['mch_id'];
           
            $this->appid=$config['appid'];
           
            $this->keys=$config['key'];
           
            $this->openid=$openid;
        }
        //小程序端-支付--改 h5支付 
        public function payset($autId,$price){
          $data=[];
          $appid =   $this->appid;//appid.如果是公众号 就是公众号的appid
          $body = $this->shopName;
          $total_fee = $price * 100;// 微信支付单位是分，所以这里需要*100
          $mch_id =$this->mchid; //商户号
          $nonce_str = $this->nonce_str();//随机字符串
          $notify_url = _doadmin.'api/returnpay/returnwxpayROrder';//回调的url
          $openid =$this->openid;
          $out_trade_no = $this->order_number($openid);//商户订单号
          $spbill_create_ip = '127.0.0.1';//服务器的ip【自己填写】;
         
          $trade_type ='MWEB'; //'JSAPI';//交易类型 默认
            $post=[];
            $post['appid'] = $appid;
            $post['body'] = $body;
            $post['mch_id'] = $mch_id;
            $post['nonce_str'] = $nonce_str;//随机字符串
            $post['notify_url'] = $notify_url;
            $post['openid'] = $openid;
            $post['out_trade_no'] = $out_trade_no;
            $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
            $post['total_fee'] = $total_fee;//总金额
            $post['trade_type'] = $trade_type;
            $sign = $this->sign($post);//签名
            $post['sign']=$sign;
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
           
             $post_xml = '<xml><appid>' . $appid . '</appid> <body>' . $body . '</body> <mch_id>' . $mch_id . '</mch_id><nonce_str>' . $nonce_str . '</nonce_str>
            <notify_url>' . $notify_url . '</notify_url>
            <openid>' . $openid . '</openid>
            <out_trade_no>' . $out_trade_no . '</out_trade_no>
            <spbill_create_ip>' . $spbill_create_ip . '</spbill_create_ip>
            <total_fee>' . $total_fee . '</total_fee>
            <trade_type>' . $trade_type . '</trade_type>
            <sign>' . $sign . '</sign>
            </xml> ';
           
            $xml= $this->http_request($url,$post_xml);
            $array = $this->xml($xml);//全要大写
            if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
                $time = time();
                $tmp = [];//临时数组用于签名
                $tmp['appId'] = $appid;
                $tmp['nonceStr'] = $nonce_str;
                $tmp['package'] = 'prepay_id=' . $array['PREPAY_ID'];
                $tmp['signType'] = 'MD5';
                $tmp['timeStamp'] = "$time";
                $data['state'] = 200;
                $data['timeStamp'] = "$time";//时间戳
                $data['nonceStr'] = $nonce_str;//随机字符串
                $data['signType'] = 'MD5';//签名算法，暂支持 MD5
                $data['package'] = 'prepay_id=' . $array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
                $data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
                $data['out_trade_no'] = $out_trade_no;
                if(1){
                    $info=Db::name("wxpay_log")->insert([
                        "no"=>$out_trade_no,
                        "price"=>$price,
                        "type"=>0,
                        "status"=>0,
                        "aut_id"=>$autId,
                        "addtime"=>time()
                    ]);
                }
            } else {
                $data['state'] = 0;
                $data['text'] = "错误";
                $data['RETURN_CODE'] = $array['RETURN_CODE'];
                $data['RETURN_MSG'] = $array['RETURN_MSG'];
            }
           // $data['appid']=$appid;
           // file_get_contents("http://dump.fuls.top?data=".json_encode($data));
           
            //"provider": "wxpay",
            // $datas['provider']="wxpay";
            // $datas['orderInfo']=$data;
                      
            return $data;
        }
         //获取xml
    private function xml($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = [];
        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }
      //随机32位字符串
        private function nonce_str()
        {
            $result = '';
            $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
            for ($i = 0; $i < 32; $i++) {
                $result .= $str[rand(0, 48)];
            }
            return $result;
        }
        private function order_number($openid){
            return md5(time().$openid.uniqid());
        }
        //签名 $data要先排好顺序
    private function sign($data)
    {
        $stringA = '';
        foreach ($data as $key => $value) {
            if (!$value) continue;
            if ($stringA) $stringA .= '&' . $key . "=" . $value;
            else $stringA = $key . "=" . $value;
        }
        $wx_key = $this->keys;//申请支付后有给予一个商户账号和密码，登陆后自己设置的key
        $stringSignTemp = $stringA . '&key=' . $wx_key;
        return strtoupper(md5($stringSignTemp));
    }
    //curl请求
    public function http_request($url, $data = null, $headers = array())
    {
        $curl = curl_init();
        if (count($headers) >= 1) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);


        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
           
        }